package com.xjj.sso.server.util;

import java.io.IOException;
import java.util.Collection;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.xjj.sso.server.SSOConstants;
import com.xjj.sso.server.cache.TicketCache;
import com.xjj.sso.server.rabbitmq.MqMessage;
import com.xjj.sso.server.rabbitmq.Producer;
import com.xjj.sso.server.ticket.ServiceTicket;

public final class SSOUtils {

	private SSOUtils() {
	}

	public static void assertNotNull(final Object object, final String message) {
		if (object == null) {
			throw new IllegalArgumentException(message);
		}
	}

	@SuppressWarnings("rawtypes")
	public static void assertNotEmpty(final Collection c, final String message) {
		assertNotNull(c, message);
		if (c.isEmpty()) {
			throw new IllegalArgumentException(message);
		}
	}

	public static void assertTrue(final boolean cond, final String message) {
		if (!cond) {
			throw new IllegalArgumentException(message);
		}
	}

	public static boolean isEmpty(final String string) {
		return string == null || string.length() == 0;
	}

	public static boolean isNotEmpty(final String string) {
		return !isEmpty(string);
	}

	public static boolean isBlank(final String string) {
		return isEmpty(string) || string.trim().length() == 0;
	}

	public static boolean isNotBlank(final String string) {
		return !isBlank(string);
	}
	
	
	/**
	 * 通知退出
	 * @param ticket
	 */
	public static void noticeClientLogout(ServiceTicket ticket)
	{
		//http方式通知退出
		if(SSOConstants.SSO_NOTIFICATION_TYPE.equals("http"))
		{
			String logoutURL= ticket.getHost()+"?requestLogout="+ticket.getId();
			System.out.println("========logoutURL=="+logoutURL);
			SSOUtils.clientLogout(logoutURL);
			return;
		}
		
		//rabbitmq方式通知退出
		if(SSOConstants.SSO_NOTIFICATION_TYPE.equals("rabbitmq"))
		{
			//发送rabbitmq单点退出消息
			sentLogoutMQ(ticket.getId());
			TicketCache.removeServiceTicket(ticket.getId());
			return;
		}
	}

	/**
	 * rabbitMQ发送退出topic消息
	 * @param stId
	 */
	public static void sentLogoutMQ(String stId)
	{
		try {
			//rabbitMQ发送退出广播消息
			Producer p = new Producer("sso.logout");
			MqMessage msg = new MqMessage("logout",stId);
			String jsonMsg = JsonUtil.toJSONString(msg);
			p.sendMessage(jsonMsg.getBytes("utf-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 通知客户端退出
	 * @param url
	 */
	public static void clientLogout(String url){
    	CloseableHttpClient  httpClient=HttpClients.createDefault();  
		HttpPost httppost = new HttpPost(url); 
		try {
			
			httpClient.execute(httppost);
			
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }
}